package com.team9.fitness.controller;

import com.team9.fitness.dto.FitnessRequest;
import com.team9.fitness.service.ZRDDSSendService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

/**
 * Fitness代理控制器
 * 接收前端请求并通过ZRDDS转发给fitness-get模块
 */
@Slf4j
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class FitnessProxyController {

    @Autowired
    private ZRDDSSendService zrddsSendService;

    /**
     * 通用GET请求处理
     */
    @GetMapping("/**")
    public CompletableFuture<ResponseEntity<?>> handleGetRequest(
            HttpServletRequest request,
            @RequestParam Map<String, Object> params) {

        String path = getRequestPath(request);
        String requestType = determineRequestType(path, "GET");

        FitnessRequest fitnessRequest = createFitnessRequest(request, "GET", path, params, null);
        fitnessRequest.setRequestType(requestType);

        return processRequest(fitnessRequest);
    }

    /**
     * 通用POST请求处理
     */
    @PostMapping("/**")
    public CompletableFuture<ResponseEntity<?>> handlePostRequest(
            HttpServletRequest request,
            @RequestBody(required = false) Object body) {

        String path = getRequestPath(request);
        String requestType = determineRequestType(path, "POST");

        FitnessRequest fitnessRequest = createFitnessRequest(request, "POST", path, null, body);
        fitnessRequest.setRequestType(requestType);

        return processRequest(fitnessRequest);
    }

    /**
     * 通用PUT请求处理
     */
    @PutMapping("/**")
    public CompletableFuture<ResponseEntity<?>> handlePutRequest(
            HttpServletRequest request,
            @RequestBody(required = false) Object body) {

        String path = getRequestPath(request);
        String requestType = determineRequestType(path, "PUT");

        FitnessRequest fitnessRequest = createFitnessRequest(request, "PUT", path, null, body);
        fitnessRequest.setRequestType(requestType);

        return processRequest(fitnessRequest);
    }

    /**
     * 通用DELETE请求处理
     */
    @DeleteMapping("/**")
    public CompletableFuture<ResponseEntity<?>> handleDeleteRequest(
            HttpServletRequest request) {

        String path = getRequestPath(request);
        String requestType = determineRequestType(path, "DELETE");

        FitnessRequest fitnessRequest = createFitnessRequest(request, "DELETE", path, null, null);
        fitnessRequest.setRequestType(requestType);

        return processRequest(fitnessRequest);
    }

    /**
     * 处理请求
     */
    private CompletableFuture<ResponseEntity<?>> processRequest(FitnessRequest fitnessRequest) {
        return zrddsSendService.sendRequest(fitnessRequest)
                .thenApply(response -> {
                    if (response.getSuccess()) {
                        return ResponseEntity.status(response.getStatusCode())
                                .body(response.getData());
                    } else {
                        return ResponseEntity.status(response.getStatusCode())
                                .body(Map.of(
                                        "error", response.getError(),
                                        "message", response.getMessage()));
                    }
                })
                .exceptionally(throwable -> {
                    log.error("处理请求失败: {}", fitnessRequest.getRequestId(), throwable);
                    return ResponseEntity.status(500)
                            .body(Map.of(
                                    "error", "请求处理失败",
                                    "message", throwable.getMessage()));
                });
    }

    /**
     * 创建FitnessRequest对象
     */
    private FitnessRequest createFitnessRequest(
            HttpServletRequest request,
            String method,
            String path,
            Map<String, Object> params,
            Object body) {

        FitnessRequest fitnessRequest = new FitnessRequest();
        fitnessRequest.setRequestId(UUID.randomUUID().toString());
        fitnessRequest.setMethod(method);
        fitnessRequest.setPath(path);
        fitnessRequest.setParameters(params);
        fitnessRequest.setBody(body);
        fitnessRequest.setTimestamp(System.currentTimeMillis());

        // 从请求头中获取用户信息
        String userId = request.getHeader("X-User-Id");
        String token = request.getHeader("Authorization");

        if (userId != null) {
            fitnessRequest.setUserId(userId);
        }
        if (token != null) {
            fitnessRequest.setToken(token);
        }

        return fitnessRequest;
    }

    /**
     * 获取请求路径
     */
    private String getRequestPath(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        String requestURI = request.getRequestURI();
        return requestURI.substring(contextPath.length());
    }

    /**
     * 根据路径和方法确定请求类型
     */
    private String determineRequestType(String path, String method) {
        if (path.startsWith("/user")) {
            if (path.contains("/login"))
                return "USER_LOGIN";
            if (path.contains("/register"))
                return "USER_REGISTER";
            return "USER_PROFILE";
        } else if (path.startsWith("/exercise")) {
            if (path.contains("/record"))
                return "EXERCISE_RECORD";
            return "EXERCISE_INFO";
        } else if (path.startsWith("/diet")) {
            if (path.contains("/record"))
                return "DIET_RECORD";
            return "FOOD_INFO";
        } else if (path.startsWith("/community")) {
            if (path.contains("/post"))
                return "COMMUNITY_POST";
            if (path.contains("/comment"))
                return "POST_COMMENT";
        }

        // 默认类型
        return "GENERAL_REQUEST";
    }
}
